package com.triple.triplerpc.fault.tolerant;

import com.triple.triplerpc.model.RpcRequest;
import com.triple.triplerpc.model.RpcResponse;
import com.triple.triplerpc.model.ServiceMetaInfo;
import com.triple.triplerpc.server.tcp.VertxTcpClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 故障转移策略实现类 - 容错策略
 */
public class FailOverTolerantStrategy implements TolerantStrategy {

    @Override
    public RpcResponse doTolerant(Map<String, Object> context, Exception e) {
        // context里存储request, selectServiceMetaInfoList
        List<ServiceMetaInfo> serviceMetaInfoList = (List<ServiceMetaInfo>)context.getOrDefault("serviceMetaInfoList", new ArrayList<>());
        if (serviceMetaInfoList.isEmpty()) {
            throw new RuntimeException("暂无可用服务", e);
        }
        RpcRequest rpcRequest = (RpcRequest)context.getOrDefault("rpcRequest", null);
        try {
            // 每个服务都试一次
            System.out.println(" >>> 当前采用的容错机制 - 故障转移, 目前尝试转移给" + serviceMetaInfoList.get(0));
            return VertxTcpClient.doRequest(rpcRequest, serviceMetaInfoList.get(0));
        } catch (Exception err) {
            serviceMetaInfoList.remove(0);
            return doTolerant(context, e);
        }
    }

}
